package com.example.mobiletest.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mobiletest.R
import com.example.mobiletest.model.Segment

class SegmentAdapter(private var segments: List<Segment>) : RecyclerView.Adapter<SegmentAdapter.SegmentViewHolder>() {

    inner class SegmentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tvSegmentTitle: TextView = itemView.findViewById(R.id.tvSegmentTitle)
        private val tvOrigin: TextView = itemView.findViewById(R.id.tvOrigin)
        private val tvOriginCity: TextView = itemView.findViewById(R.id.tvOriginCity)
        private val tvDestination: TextView = itemView.findViewById(R.id.tvDestination)
        private val tvDestinationCity: TextView = itemView.findViewById(R.id.tvDestinationCity)
        private val tvUrl: TextView = itemView.findViewById(R.id.tvUrl)

        fun bind(segment: Segment, position: Int) {
            tvSegmentTitle.text = "航段 ${position + 1} (ID: ${segment.id})"
            
            val origin = segment.originAndDestinationPair.origin
            val destination = segment.originAndDestinationPair.destination
            
            tvOrigin.text = "${origin.displayName} (${origin.code})"
            tvOriginCity.text = segment.originAndDestinationPair.originCity
            tvDestination.text = "${destination.displayName} (${destination.code})"
            tvDestinationCity.text = segment.originAndDestinationPair.destinationCity
            tvUrl.text = origin.url
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SegmentViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_segment, parent, false)
        return SegmentViewHolder(view)
    }

    override fun onBindViewHolder(holder: SegmentViewHolder, position: Int) {
        holder.bind(segments[position], position)
    }

    override fun getItemCount(): Int = segments.size

    fun updateSegments(newSegments: List<Segment>) {
        segments = newSegments
        notifyDataSetChanged()
    }
}